﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;

namespace ExpreRec.Logic.Preprocessing
{
    public static class Processor
    {
        public static IplImage ReSize(IplImage originalImage, double ratio, Interpolation interpolation)
        {
            return ReSize(originalImage, new CvSize(Cv.Round(originalImage.Width / ratio), Cv.Round(originalImage.Height / ratio)), interpolation);
        }

        public static IplImage ReSize(IplImage originalImage, CvSize dstSize, Interpolation interpolation)
        {
            IplImage smallImg = new IplImage(dstSize, originalImage.Depth, originalImage.NChannels);
            Cv.Resize(originalImage, smallImg, interpolation);
            return smallImg;
        }

        public static IplImage RGBToGray(IplImage color)
        {
            IplImage gray = new IplImage(color.Size, BitDepth.U8, 1);
            Cv.CvtColor(color, gray, ColorConversion.BgrToGray);
            return gray;
        }

        public static IplImage EqualizeHist(IplImage img)
        {
            IplImage dst = new IplImage(img.Size, img.Depth, img.NChannels);
            Cv.EqualizeHist(img, dst);
            return dst;
        }

        public static IplImage RotateLeft(IplImage img)
        {
            CvSize originalSize = img.GetSize();

            CvSize size = new CvSize(originalSize.Height, originalSize.Width);

            IplImage dst = new IplImage(size, img.Depth, img.NChannels);

            CvPoint2D32f center = new CvPoint2D32f(originalSize.Width / 2, originalSize.Width / 2);

            using (CvMat mapMatrix = new CvMat(2, 3, MatrixType.F32C1))
            using (CvMat mapMatrixDst = Cv.GetRotationMatrix2D(center, 90, 1.0))
            {
                Cv.WarpAffine(img, dst, mapMatrixDst);
            }

            return dst;
        }

        public static IplImage RotateRight(IplImage img)
        {
            CvSize originalSize = img.GetSize();

            CvSize size = new CvSize(originalSize.Height, originalSize.Width);

            IplImage dst = new IplImage(size, img.Depth, img.NChannels);

            CvPoint2D32f center = new CvPoint2D32f(originalSize.Height / 2, originalSize.Height / 2);

            using (CvMat mapMatrix = new CvMat(2, 3, MatrixType.F32C1))
            using (CvMat mapMatrixDst = Cv.GetRotationMatrix2D(center, -90, 1.0))
            {
                Cv.WarpAffine(img, dst, mapMatrixDst);
            }

            return dst;
        }
    }
}